package com.sixbro.orm.jpa.service;

import com.sixbro.orm.jpa.entity.Permission;
import com.sixbro.orm.jpa.repository.PermissionRepository;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *
 * </p>
 *
 * @author: Mr.Lu
 * @since: 2021-12-15 9:02
 */
@Service
public class PermissionService {

    private final PermissionRepository permissionRepository;

    public PermissionService(PermissionRepository permissionRepository) {
        this.permissionRepository = permissionRepository;
    }

    public Page<Permission> findPermissionByPage(int page, int size, String name, String code){
        Specification<Permission> specificationQuery = new Specification<>() {
            @Override
            public Predicate toPredicate(Root<Permission> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                if (StringUtils.isNoneBlank(name)) {
                    Path<String> pname = root.get("name");
                    Predicate predicate = criteriaBuilder.like(pname, "%" + name + "%");
                    list.add(criteriaBuilder.and(predicate));
                }

                if (StringUtils.isNoneBlank(code)) {
                    Path<String> pcode = root.get("code");
                    Predicate predicate = criteriaBuilder.equal(pcode, code);
                    list.add(criteriaBuilder.and(predicate));
                }
                Predicate[] p = new Predicate[list.size()];
                return criteriaBuilder.and(list.toArray(p));
            }
        };
        Page<Permission> permissions = permissionRepository.findAll(specificationQuery, PageRequest.of(page - 1, size));
        return permissions;
    }
}
